﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MagicalDesktop.Simulation;
using System.IO;
using System.Xml.Serialization;

namespace MagicalDesktop
{
    public class Shell : NotifyPropertyChanged
    {
        private static Shell _instance;
        public static Shell Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Shell();
                return _instance;
            }
        }

        private Shell()
        {
            using (var file = File.OpenRead(@"Simulation\Services.xml"))
            {
                var serializer = new XmlSerializer(typeof(Service[]));
                Services = serializer.Deserialize(file) as Service[];
            }
            using (var file = File.OpenRead(@"Simulation\Users.xml"))
            {
                var serializer = new XmlSerializer(typeof(User[]));
                Users = serializer.Deserialize(file) as User[];
            }
            using (var file = File.OpenRead(@"Simulation\Groups.xml"))
            {
                var serializer = new XmlSerializer(typeof(Group[]));
                Groups = serializer.Deserialize(file) as Group[];
            }

            foreach (var user in Users)
            {
                user.Services = Services.Where(s => user.ServiceNames.Contains(s.Name)).ToArray();
            }
            foreach (var group in Groups)
            {
                group.Users = Users.Where(u => u.Group == group.Name).ToArray();
            }
        }

        public Action RefreshView { get; set; }
        public Action<User> UserButtonClicked { get; set; }

        public Service[] Services { get; private set; }
        public User[] Users { get; private set; }
        public Group[] Groups { get; private set; }

        public Service[] ActiveServices
        {
            get
            {
                return Services.Where(s => s.LoggedIn).ToArray();
            }
        }
    }
}
